var map;
var geocoder;
var marker = null;

var thisLatLng = null;

$(document).ready(function() {
	
	var myOptions = {
	    zoom: 16,
	    mapTypeControl: false,
	    navigationControl: true,
	    navigationControlOptions: {
	        style: google.maps.NavigationControlStyle.SMALL
	    },
	    mapTypeId: google.maps.MapTypeId.ROADMAP
	};
		
	map = new google.maps.Map(document.getElementById("map"), myOptions);
	
	var latitude = $('#lat').val();
	var longitude = $('#lng').val();
	
	setupMarker(latitude, longitude);
	initialLocation = new google.maps.LatLng(latitude, longitude);
	map.setCenter(initialLocation);
	
	geocoder = new google.maps.Geocoder();
	
	$('#address').after('<a class="linkButtonNoText ui-state-default" id="lookupAddress">Locate</a>');
	$('#lookupAddress').css('margin-left', '5px')
	                   .click(function(e) {
	                	  e.preventDefault();
	            	      lookupAddress($('#address').val());
	                   });	  	
});

function lookupAddress(address) {
    
	geocoder.geocode( { 'address': address}, function(results, status) {
      
		if (status == google.maps.GeocoderStatus.OK) {
			setupMarker(results[0].geometry.location.lat(), results[0].geometry.location.lng());
	        map.panTo(results[0].geometry.location);
		} else {
			alert("Geocode was not successful for the following reason: " + status);
	    }
    });
}

function setupMarker(latitude, longitude) {
	
	$('#lat').val(latitude);
	$('#lng').val(longitude);
	
	thisLatLng = new google.maps.LatLng(latitude, longitude);
	
	if (marker == null) {
		marker = new google.maps.Marker({
	        position: thisLatLng, 
	        map: map,
	        draggable: true,
	        title:"This sign!"
	    });
		
		google.maps.event.addListener(marker, 'drag', function() {
		    var thisLatLng = marker.getPosition();
		    $('#lat').val(thisLatLng.lat());
		    $('#lng').val(thisLatLng.lng());
		});
		
	} else {
		marker.setPosition(thisLatLng);
	}
}